package com.hst.web.sys.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.core.json.JsonUtil;
import com.hst.web.base.entity.TAccountIdentity;
import com.hst.web.base.entity.TAccountInfo;
import com.hst.web.base.entity.TCompanyEmployee;
import com.hst.web.common.utils.ConstantUtil;
import com.hst.web.sys.entity.TUser;
import com.hst.web.sys.entity.TUserDept;
import com.hst.web.sys.entity.TUserRole;
import com.hst.web.sys.ui.EmployeeUpgrade;
import com.hst.web.sys.ui.User;

@Service
@Transactional
public class UserService {

	@Autowired
	ISQLDao sql;

	@Autowired
	IORDao dao;

	/*
	 *  账户升级
	 */
	public void upgrade(String roleId,String userId,Model m) {
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"userid",userId));
		//找到所有当前账号拥有角色，先删除
		List<TUserRole> roles = dao.list(TUserRole.class,querys);
		for(TUserRole role:roles) {
			dao.delete(role);
		}
		//添加角色
		TUserRole obj = new TUserRole();
		obj.setRoleid(roleId);
		obj.setUserid(userId);
		dao.save(obj);
		m.addAttribute("msg","success");
	}

	/**
	 * 分配用户部门权限
	 */
	public void allotDept(String userId,String depts) {
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"userid",userId));
		List<TUserDept> objs = dao.list(TUserDept.class,querys);
		for(TUserDept obj:objs) {
			dao.delete(obj);
		}
		String[] deptCodes = depts.split(",");
		for(int i=0;i<deptCodes.length;i++) {
			if(StringUtils.isNotEmpty(deptCodes[i])) {
				TUserDept dept = new TUserDept();
				dept.setUserid(userId);
				dept.setDeptCode(deptCodes[i]);
				dao.save(dept);
			}
		}
	}

	/**
	 * 停用账号
	 * @param users
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	public void disable(List<User> users,Model m) throws JsonGenerationException, JsonMappingException, IOException {
		for(User u:users) {
			TUser us = dao.get(TUser.class, u.getId());
			us.setValidflag("2");
			us =dao.update(us);
			u.setValidflag("2");
		}
		m.addAttribute("users",JsonUtil.toString(users));
	}

	/**
	 * 启用账号
	 * @param users
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	public void enable(List<User> users,Model m) throws JsonGenerationException, JsonMappingException, IOException {
		for(User u:users) {
			TUser us = dao.get(TUser.class, u.getId());
			us.setValidflag("1");
			us =dao.update(us);
			u.setValidflag("1");
		}
		m.addAttribute("users",JsonUtil.toString(users));
	}
	
	/**
	 * 允许预约
	 * @param users
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	public void appointmentEnable(List<User> users,Model m) throws JsonGenerationException, JsonMappingException, IOException {
		for(User u:users) {
			TUser us = dao.get(TUser.class, u.getId());
			us.setAppointmentFlag("1");
			us = dao.update(us);
			u.setAppointmentFlag("1");
		}
		m.addAttribute("users", JsonUtil.toString(users));
	}

	/**
	 * 禁止预约
	 * @param users
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	public void appointmentDisable(List<User> users,Model m) throws JsonGenerationException, JsonMappingException, IOException {
		for(User u:users) {
			TUser us = dao.get(TUser.class, u.getId());
			us.setAppointmentFlag("0");
			us = dao.update(us);
			u.setAppointmentFlag("0");
		}
		m.addAttribute("users", JsonUtil.toString(users));
	}
	/**
	 * 修改用户角色
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	public void changeRole(User user,String role,Model m) throws JsonGenerationException, JsonMappingException, IOException {
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"userid",user.getId()));
		List<TUserRole> rels = dao.list(TUserRole.class,querys);
		for(TUserRole rel:rels) {
			dao.delete(rel);
		}
		TUserRole rel = new TUserRole();
		rel.setRoleid(role);
		rel.setUserid(user.getId());
		dao.save(rel);
		user.setRole(role);
		m.addAttribute("user", JsonUtil.toString(user));
	}

	/**
	 * 账号升级
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	public void employeeUpgrade(String obj,String account,String role,String pwd,Model m) throws JsonParseException, JsonMappingException, IOException {
		EmployeeUpgrade emp = JsonUtil.read(obj, EmployeeUpgrade.class);
		String employeeCode = emp.getEmployeeCode();
		//先去查询是否员工有账号
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"employeeCode",emp.getEmployeeCode()));
		List<TUser> users = dao.list(TUser.class,querys);

		if(users.size() > 0) { // 已经存在账号
			TUser user = users.get(0);
			//根据角色修正UserTypeOld字段映射值
			user.setUserTypeOld(ConstantUtil.USETYPEMAP.get(role));
			dao.update(user);
			
			querys = new ArrayList<ORQuery>();
			querys.add(new ORQuery(Op.eq,"userid",user.getId()));
			List<TUserRole> rels = dao.list(TUserRole.class,querys);
			for(TUserRole rel:rels) {
				dao.delete(rel);
			}
			TUserRole rel = new TUserRole(); // 保存新的关联关系
			rel.setRoleid(role);
			rel.setUserid(user.getId());
			dao.save(rel);
			
			//同步更新TAccountInfo表的useType字段
			String userName = vaildateAccountIdentity(employeeCode);
			if (StringUtils.isNotEmpty(userName)) {
				TAccountInfo accountInfo = dao.get(TAccountInfo.class, userName);
				if (accountInfo != null) {
					accountInfo.setUseType(ConstantUtil.USETYPEMAP.get(role));
					dao.update(accountInfo);
				}
			}
			m.addAttribute("success","success");
		} else { //账号不存在
			String userName = vaildateAccountIdentity(emp.getEmployeeCode());
			if(StringUtils.isNotEmpty(userName)) { //实名认证通过
				TAccountInfo account1 = dao.get(TAccountInfo.class, userName);
				if(account1 != null) {
					TUser newUser = new TUser();
					newUser.setPassword(account1.getPassword());
					newUser.setOperatorNbr(account1.getUserName());
					newUser.setEmployeeCode(emp.getEmployeeCode());
					newUser.setLoginName(emp.getFullName());
					newUser.setValidflag("1");  //是否有效
					newUser.setUserType("2"); //用户类型企业用户
					//根据角色修正UserTypeOld字段映射值
					newUser.setUserTypeOld(ConstantUtil.USETYPEMAP.get(role));
					newUser = dao.save(newUser);

					TUserRole rel = new TUserRole(); //添加用户角色
					rel.setRoleid(role);
					rel.setUserid(newUser.getId());
					dao.save(rel);
					
					//同步更新TAccountInfo表的useType字段
					account1.setUseType(ConstantUtil.USETYPEMAP.get(role));
					dao.update(account1);
					
					m.addAttribute("success", "success");
				}else {
					m.addAttribute("errorCode","error");
					m.addAttribute("msg","未实名认证的人员不能赋职");
				}
			}else {
				m.addAttribute("errorCode","error");
				m.addAttribute("msg","未实名认证的人员不能赋职");
			}
		}
	}

	/**
	 * 校验是否实名认证
	 */
	public String vaildateAccountIdentity(String employeeCode) {
		if (StringUtils.isNotEmpty(employeeCode)) {
			TCompanyEmployee employee = dao.get(TCompanyEmployee.class, employeeCode);
			List<ORQuery> querys = new ArrayList<ORQuery>();
			if (employee != null) {
				querys.add(new ORQuery(Op.eq,"papersNumber",employee.getPapersNumber()));
				querys.add(new ORQuery(Op.eq,"papersType",employee.getPapersType()));
//				querys.add(new ORQuery(Op.eq,"fullname",employee.getFullname()));
				List<TAccountIdentity> identities = dao.list(TAccountIdentity.class,querys);
				if(identities.size() > 0) {
					return identities.get(0).getUserName();
				} else {
					return null;
				}
			} else {
				return null;
			}

		} else {
			return null;
		}
	}
}
